<?php
/**
 * 编辑页面保存数据
 */
namespace App\Http\Controllers;

use app\Http\Models\AuthGroupModel;
use App\Http\Models\ClearModel;
use App\Http\Models\LotteryLogModel;
use App\Http\Models\LotteryModel;
use App\Http\Models\LotteryPrizeLogModel;
use App\Http\Models\VipLevelModel;
use Illuminate\Http\Request;
use App\Http\Models\ProjectModel;
use App\Http\Models\TemplateModel;
use App\Http\Models\TemplateJsonModel;
use App\Http\Models\SettingsModel;
use App\Http\Models\MarketingModel;
use App\Http\Models\FormDictModel;
use App\Http\Models\LotteryPrizeModel;
use App\Http\Models\GameCodeModel;
use App\Http\Models\VipSettingsModel;
use App\Http\Models\VipModel;
use Mockery\Exception;

class EditController extends HomeController
{

    protected $_unsetSettingsKey = [
        'endtime',
        'settranscode',
        'raffletype',
        'setscorelimit',
        'setlimittimes',
        'ranking1',
        'hidden_ranking',
        'is_display_settranscode',
        'settranscode'
    ];
    private $_formKey = 'formitems';
    private $_baseInfoKey = 'baseinfo';
    private $_noTransCode   = array("qiandao");
    private $_noWxRedPack   = array('honghuangyuebin', 'nocp', 'guacai');
    private $_noUnlimit     = array('dazhuanpan'=>5);

    /**
     * 保存编辑信息
     * author wangyongqiang
     * part1 templatejson
     * part2 lotteryinfo
     * part3 marketinfo
     */
    public function save(Request $request){
        try{
            //基本校验
            $this->validate($request, ['apptoken' => 'required']);
            $apptoken = $request->input('apptoken');
            $projectInfo = ProjectModel::info($apptoken);//获取项目信息
            $appid = $projectInfo->id;

            //获取POST参数
            $inputRaffletype = $request->input('raffletype');
            $inputExtwayList = $request->input('extwayList');

            $updatePrize = $update = array();
            $marketType = null;
            if($projectInfo->raffletype != $inputRaffletype) {
                $templateInfo = TemplateModel::where(['id'=>$projectInfo->template_id])->first();
                $marketType = $inputRaffletype;

                $raffletypes = MarketingModel::TYPE_NONE;
                if($templateInfo && '' != $templateInfo->raffletypes) $raffletypes = $templateInfo->raffletypes;
                $raffletypeArrs = explode(',', $raffletypes);

                if (!in_array($marketType, $raffletypeArrs)) {
                    $marketType = $raffletypeArrs[0];
                }

                $updatePrize['raffletype'] = $marketType;
            }

            // 发布平台设置
            if($marketType != MarketingModel::TYPE_INDIANA) {
                $publishPlatformStr = $inputExtwayList;
                if($publishPlatformStr) {
                    $publishPlatformStr = htmlspecialchars_decode($publishPlatformStr);
                    $publish_platforms_number = $this->setPublishPlatform(json_decode($publishPlatformStr, true));
                    if($publish_platforms_number != $projectInfo->publish_platform) {
                        $updatePrize['publish_platform'] = $publish_platforms_number;
                    }
                }
            }
            /*
             * bee平台
             * if(!empty($updatePrize)) {
                D('Project')->where(array('id' => $appid))->data($updatePrize)->save();
                D("Project")->delCache($appid, $token);
            }*/

            //step2.保存营销信息
            $data = array();

            $inputCriteria  = $request->input('criteria');//todo wayne add
            $inputPrizes    = $request->input('prizes');
            $inputForms     = $request->input('forms');

            $data['criteria'] = $inputCriteria;
            $data['criteria']['formitems'] = json_encode($data['criteria']['formitems']);
            $data['prizes'] = $inputPrizes;

            //排行榜显示
            if($projectInfo['setrankbtn'] == 0){
                $raffle_ranking_val = $data['criteria']['is_display_ranking'] ? 1 : 0;
                VipSettingsModel::updateItemValue($appid, 'is_display_ranking', $raffle_ranking_val );
            }
            if(isset($data['criteria']['is_display_settranscode'])) unset($data['criteria']['is_display_settranscode']);

            $raffletype = LotteryPrizeModel::LOT_TYPE_RAFFLE;
            $data['raffletype'] = $raffletype;
            $data['criteria']['raffletype'] = $raffletype;
            $data['criteria']['setwxredpack'] = 0;

            //处理营销设置奖品
            if(isset($data['prizes']) && is_array($data['prizes'])) {
                foreach ($data['prizes'] as $key => $val) {
                    if(isset($val['lot_exchangenum'])) {
                        $val['lot_code_setting']['lot_exchangenum'] = (int)$val['lot_exchangenum'];
                        unset($val['lot_exchangenum']);
                    }
                    if(isset($val['prizes_link']) && $val['prizes_link']!=""){
                        $val['prizes_link'] = str_replace(array(" ","  ","'",'"'),"",$val['prizes_link']);
                        $val['prizes_link'] = str_replace("&amp;","&",$val['prizes_link']);
                    }
                    if($val['lot_type'] == LotteryPrizeModel::LOT_TYPE_REDPACK && isset($val['lot_unit_price'])) {
                        //处理红包
                        $lotCodeSet = array();
                        if(isset($val['lot_code_setting'])) {

                            $lotCodeSet = $val['lot_code_setting'];

                            $lot_unit_price = sprintf("%.2f", $val['lot_unit_price']);
                            $lot_unit_price_number = (int)($lot_unit_price*100);
                            $lot_unit_price = $lot_unit_price_number<100 ? 1 : $lot_unit_price;
                            $lot_unit_price = $lot_unit_price_number>10000 ? 100 : $lot_unit_price;

                            $lotCodeSet['lot_unit_price']      = $lot_unit_price;
                            $lotCodeSet['lot_amount_price']    = sprintf("%.2f", $lot_unit_price * (int)$val['lot_count']);

                            $lotCodeSet['lot_authorize_link']      = 0;
                            $lotCodeSet['lot_authorize_status']    = 0;

                            if(isset($lotCodeSet['lot_authorize_link']) && $lotCodeSet['lot_authorize_link'])
                                $lotCodeSet['lot_authorize_link'] = 1;

                            if(isset($lotCodeSet['lot_authorize_status']) && $lotCodeSet['lot_authorize_status'])
                                $lotCodeSet['lot_authorize_status'] = 1;
                        }

                        unset($val['lot_unit_price'], $val['lot_amount_price']);

                        $val['lot_code_setting'] = $lotCodeSet;

                        if($data['criteria']['setwxredpack'] ==0 ) $data['criteria']['setwxredpack'] = 1;
                    }
                    if($val['lot_type'] == LotteryPrizeModel::LOT_TYPE_CREDIT && isset($val['lot_unit_credit'])) {
                        //处理积分
                        if(isset($val['lot_code_setting'])) {
                            $lot_unit_credit = sprintf("%.2f", $val['lot_unit_credit']<10 ? 10 : $val['lot_unit_credit']);
                            $val['lot_code_setting']['lot_unit_credit']      = sprintf("%.2f", $lot_unit_credit);
                            $val['lot_code_setting']['lot_amount_credit']    = sprintf("%.2f", $lot_unit_credit*(int)$val['lot_count']/100);
                        }

                        unset($val['lot_unit_credit'], $val['lot_amount_credit']);

                        if($data['criteria']['setwxcredit'] ==0 ) $data['criteria']['setwxcredit'] = 1;
                    }

                    //qianglibao
                    if($projectInfo['iscollect']==4){
                        //每个礼包奖品数
                        $val['lot_code_setting']['lot_gift_prizes'] || $val['lot_code_setting']['lot_gift_prizes']=1;
                        //平分的人数
                        $val['lot_code_setting']['lot_gift_peoplenum'] || $val['lot_code_setting']['lot_gift_peoplenum']=1;
                        //凑齐人数
                        $val['lot_code_setting']['lot_gift_minute'] || $val['lot_code_setting']['lot_gift_minute']=1;
                        //奖品组数
                        $val['lot_code_setting']['lot_group_num'] = isset($val['lot_group_num']) && $val['lot_group_num'] ? $val['lot_group_num'] : 1;
                    }
                    $data['prizes'][$key] = $val;
                }
            }
            //同步营销数据到数据库
            $res = array();
            $options = $data['criteria'];
            // 同步setting配置
            $criteriaFlag = false;
            if (!empty($options)){
                // 处理单个值，先全部重置成无效，后期需要优化
                $criteriaCond = array();
                $criteriaCond['appid'] = $appid;
                $criteriaCond['item_key'] = array('in', array_keys($options));
                $criteriaCond['status'] = SettingsModel::STATUS_ACTIVE;
                $criteriaFieldsData = array('status'=>SettingsModel::STATUS_DELETED, 'modify_time'=>time());
                // 先清理
                SettingsModel::where($criteriaCond)->update($criteriaFieldsData);
                $data = array();
                foreach ($options as $key=>$value) {
                    if($key == 'raffletype' || $key == 'endtime' || $key == 'settranscode' || $key == 'setscorelimit' || $key == 'setlimittimes') {
                        continue;
                    }
                    $data[] = array(
                        'appid'=>$appid,
                        'item_key'=>$key,
                        'item_value'=>(is_array($value) ? json_encode($value) : $value),
                        'status'=>SettingsModel::STATUS_ACTIVE,
                        'create_time'=>time(),
                        'modify_time'=>0
                    );
                }

                $criteriaFlag = SettingsModel::insert($data);
            }
            $res['criteria'] = $criteriaFlag;

            // 将endtime,raffletype 更新到project表中
            $updatePrize = array();
            if(isset($data['criteria']['endtime'])) $updatePrize['endtime'] = $data['criteria']['endtime'];
            if(isset($data['criteria']['raffletype'])) $updatePrize['raffletype'] = $data['criteria']['raffletype'];
            if(isset($data['criteria']['settranscode'])) $updatePrize['settranscode'] = $data['criteria']['settranscode'];
            if(isset($data['criteria']['setwxredpack'])) $updatePrize['setwxredpack'] = $data['criteria']['setwxredpack'];
            if(isset($data['criteria']['setwxcredit'])) $updatePrize['setwxcredit'] = $data['criteria']['setwxcredit'];
            $updatePrize['modify_time'] = time();

            if(!empty($updatePrize)) {
                ProjectModel::where(array('id' => $appid))->update($updatePrize);
                ClearModel::clear_project($appid, $projectInfo->token);
            }
            unset($updatePrize);

            //同步奖品
            $raffletype = isset($data['raffletype']) ? $data['raffletype'] : false;
            $prizes = $data['prizes'] && is_array($data['prizes']) ? $data['prizes'] : array();
            if(!empty($prizes)) {
                //$res['prizes'] = $this->syncPrizes($appid, $raffletype, $prizes);//bee code
                // 处理prize，优化新增/修改/删除方法
                $lot_type = LotteryPrizeModel::checkType($raffletype);
                //$online = $lotteryPrizeModel->getPrize($appid, false, false, $lotteryPrizeModel::STATUS_ACTIVE);
                $onlinePrizes = LotteryPrizeModel::getPrize($appid, false, false, LotteryPrizeModel::STATUS_ACTIVE, array('id', 'lot_count', 'lot_code_setting', 'lot_type'));
                $online = array_keys($onlinePrizes);
                $online = $online ? $online : array();
                $offline = $update = array();

                $vipLevel = $this->user['vipLevel'];
                $uid = $this->user['uid'];

                $prize_number   = VipLevelModel::getVipPowerByDb($vipLevel, 'editor_prize_category_numbers' );
                $lottery_number = VipLevelModel::getVipPowerByDb($vipLevel, 'editor_prize_numbers' );
                $prize_number = (int) $prize_number;
                $lottery_number = (int) $lottery_number;
                $lot_total = $lot_total_tmp = $delete_redpack_lot_total = $active_redpack_lot_total = 0;

                $data = array();
                foreach ($prizes as $key => $prize) {
                    if($prize['lot_id'] != 0 || !$prize_number || $key < $prize_number) {
                        if( $lottery_number ) {
                            $lot_total_tmp = $lot_total;
                            $lot_total += $prize['lot_count'];
                            if($lot_total > $lottery_number) {
                                if(! ($prize['lot_id'] != 0 && isset($onlinePrizes[$prize['lot_id']]) && ($onlinePrizes[$prize['lot_id']]['lot_count']==$prize['lot_count']))) {
                                    $lot_count = $lottery_number-$lot_total_tmp;
                                    $prize['lot_count'] = $lot_count>0 ? $lot_count : 0;
                                }
                            }
                        }

                        $lot_code_setting = '';
                        if (!empty($prize['lot_code_setting'])) {
                            $lot_code_setting = $prize['lot_code_setting'];
                            if (is_array($lot_code_setting) || is_object($lot_code_setting)) {
                                if(isset($lot_code_setting['num'])) $lot_code_setting['num'] = $prize['lot_count'];
                                $lot_code_setting = json_encode($lot_code_setting);
                            }
                        }

                        $data = array(
                            'lot_name'      => $prize['lot_name'],
                            'lot_count'     => $prize['lot_count'],
                            'probability'   => $prize['probability'],
                            'lot_desc'      => $prize['lot_desc'],
                            'lot_url'       => $prize['lot_url'],
                            'prizes_link'   => $prize['prizes_link'],
                            'lot_type'      => isset($prize['lot_type']) && in_array($prize['lot_type'], array(0,1,2,3,7,9,10,12,13,18,19,20,22)) ? $prize['lot_type'] : $lot_type,
                            'lot_winning_tips'  => $prize['lot_winning_tips'],
                            'lot_code_setting'  => $lot_code_setting
                        );

                        if($prize['lot_id'] == 0) {

                            if($data['lot_type'] == LotteryPrizeModel::LOT_TYPE_REDPACK) {
                                //当奖品为微信红包时，处理奖品预存金问题
                                $lot_unit_price   = isset($prize['lot_code_setting']['lot_unit_price']) ? $prize['lot_code_setting']['lot_unit_price'] : 0;
                                $lot_amount_price = $lot_unit_price*$data['lot_count'];
                                $lot_amount_price = AuthGroupModel::checkWhiteList($uid) ? $lot_amount_price*0.01 : $lot_amount_price;
                                $lot_amount_price = (float)sprintf("%.2f", $lot_amount_price);
                                if($lot_amount_price>0) {
                                    $pointRet = VipModel::addItemValue($uid, 'allredpackpoint', -$lot_amount_price);
                                    if(!$pointRet) continue;
                                }
                                $data['wxpay_fund'] = $lot_amount_price;
                                $active_redpack_lot_total++;
                            }

                            if($data['lot_type'] == LotteryPrizeModel::LOT_TYPE_CREDIT) {
                                //当奖品为积分时
                                $lot_unit_credit   = isset($prize['lot_code_setting']['lot_unit_credit']) ? $prize['lot_code_setting']['lot_unit_credit'] : 0;
                                $lot_amount_credit = isset($prize['lot_code_setting']['lot_amount_credit']) ? $prize['lot_code_setting']['lot_amount_credit'] : 0;
                                $lot_amount_credit = AuthGroupModel::checkWhiteList($uid) ? $lot_amount_credit*0.01 : $lot_amount_credit;
                                $lot_amount_credit = (float)sprintf("%.2f", $lot_amount_credit);
                                if($lot_amount_credit>0) {
                                    $pointRet = VipModel::addItemValue($uid, 'allredpackpoint', -$lot_amount_credit);
                                    if(!$pointRet) continue;
                                }
                                $data['wxpay_fund'] = $lot_amount_credit;
                                $active_redpack_lot_total++;
                            }

                            //增加
                            $lot_id = LotteryPrizeModel::addPrize($appid, $data);
                            LotteryPrizeLogModel::writePrizeLog($appid, $lot_id, $lot_type, 'add', json_encode($prize));
                            if ($lot_id && ($data['lot_type'] == LotteryPrizeModel::LOT_TYPE_EXCHANGE || $data['lot_type'] == LotteryPrizeModel::LOT_TYPE_CROWD || $data['lot_type'] == LotteryPrizeModel::LOT_TYPE_CROWDEXCHANGE || $data['lot_type']==LotteryPrizeModel::TYPE_RAFFLE_SIGNED_EXCHANGE )) {
                                //此处需要插入到gamecode 表中
                                //$this->importgamecode($appid, $lot_id, $prize['lot_code_setting'], $prize['lot_count']);
                                GameCodeModel::import($appid, $lot_id, $prize['lot_code_setting'], $prize['lot_count']);
                            }

                            if(!$lot_id && $data['lot_type'] == LotteryPrizeModel::LOT_TYPE_CREDIT) {
                                //创建奖品失败时，将积分退回
                                if($lot_amount_credit>0) {
                                    $pointRet = VipModel::addItemValue($uid, 'allredpackpoint', $lot_amount_credit);
                                }
                            }

                        } else {
                            //修改
                            $data['id'] = $prize['lot_id'];
                            LotteryPrizeModel::updatePrize($appid, $data);
                            LotteryPrizeLogModel::writePrizeLog($appid, $data['id'], $lot_type, 'update', json_encode($prize));
                            $update[] = $prize['lot_id'];
                        }
                    }
                }

                $onlineUpdate = array();
                foreach ($onlinePrizes as $onlineId => $onPrizes) {
                    if(!in_array($onPrizes['lot_type'], array(LotteryPrizeModel::LOT_TYPE_REDPACK, LotteryPrizeModel::LOT_TYPE_INDIANA, LotteryPrizeModel::LOT_TYPE_CREDIT))) {
                        $onlineUpdate[] = $onlineId;
                    }
                }

                $offline = array_diff($onlineUpdate, $update);
                if( count($offline)>0 ) {
                    LotteryPrizeModel::delPrize($appid, $offline);

                    //清理lottery记录
                    LotteryModel::delLottery($appid, $offline);

                    //清理lottery日志记录
                    LotteryLogModel::delLotteryLog($appid, $offline);

                    //if ($lot_type != $lotteryPrizeModel::LOT_TYPE_EXCHANGE && $lot_type != $lotteryPrizeModel::LOT_TYPE_CROWDEXCHANGE) {
                    //此处需要插入到gamecode 表中
                    $ret = GameCodeModel::delGameCode($appid, $offline);
                    //}

                    if ($lot_type == LotteryPrizeModel::LOT_TYPE_CROWD || $lot_type == LotteryPrizeModel::LOT_TYPE_CROWDRAFFLE || $lot_type == LotteryPrizeModel::LOT_TYPE_CROWDEXCHANGE) {
                        //删除众筹记录
                        //ClearModel::delRecordByPrizeId($appid, $offline);
                        ClearModel::empty_crowd($appid);
                    }

                    //写奖品修改日志
                    foreach ($offline as $offId) {
                        LotteryPrizeLogModel::writePrizeLog($appid, $offId, $lot_type, 'del', '');
                    }
                }

                $res['prizes'] = true;
            }

            //step3.保存项目信息
            $inputMarketingInfo = $request->input('marketinginfo');
            $inputShareInfo = $request->input('shareinfo');
            $inputOfflineInfo = $request->input('offlineinfo');
            ProjectModel::saveMarketingInfoToRedis( $appid, $inputMarketingInfo);
            ProjectModel::saveShareInfoToRedis( $appid, $inputShareInfo);
            ProjectModel::saveOfflineInfoToRedis( $appid, $inputOfflineInfo);

            //单独存储项目下线时间、下线时间
            SettingsModel::offInfoToDataBase($appid, "endtitle", $inputOfflineInfo['desc'] ? $inputOfflineInfo['desc'] : '活动已结束，敬请关注更多精彩！');
            //下线时间同步到项目表中
            ProjectModel::where(['id'=>$appid])->update(["endtime"=>$inputOfflineInfo['time']]);

            //去除项目下线时间、下线时间
            $settingData = array('marketinginfo'=>$inputMarketingInfo, 'shareinfo'=>$inputShareInfo);
            $res = SettingsModel::mapToDataBase($appid, $settingData);
            ProjectModel::syncShareInfo($appid, $projectInfo['name'], $apptoken, $inputShareInfo);
            ClearModel::clear_project($appid, $apptoken);
        }catch (\Exception $e){
            return response()->json(build_result('', '10001', $e->getMessage()));
        }
    }

    /**
     * 保存平台发布格式
     */
    private function setPublishPlatform($platforms)
    {
        $setinfo = ["1" => 1,"5" => 1];
        foreach ($platforms as $item) {
            $id = $item['typeid'];
            $setinfo[$id] = $item['selected'] ? 1 : 0;
        }
        $number = 0;
        foreach ($setinfo as $typeid => $selected) {
            if($typeid == 99 && $selected) {
                // $number += 1 * pow(10, 7);
            } elseif($selected) {
                $number += 1 * pow(10, $typeid-1);
            }
        }
        return bindec($number);
    }

    /**
     * 保存编辑信息
     * part1 templatejson
     * part2 lotteryinfo
     * part3 marketinfo
     */
    public function savebak(Request $request)
    {
        try{
            $this->validate($request, [
                'apptoken' => 'required'
            ]);
            $apptoken = $request->input('apptoken');
            $inputTemplateInfo = $request->input('templateinfo');
            $inputRuleShow = $request->input('ruleshow');
            $inputSettingInfo = $request->input('settinginfo');

            //
            $inputRaffletype = $request->input('raffletype');
            $inputCriteria = $request->input('criteria');//todo wayne add
            $inputPrizes = $request->input('prizes');
            $inputForms = $request->input('forms');

            //
            $inputMarketingInfo = $request->input('marketinginfo');
            $inputShareInfo = $request->input('shareinfo');
            $inputOfflineInfo = $request->input('offlineinfo');//todo wayne add
            $inputOfflineTime = $request->input('offlinetime');//todo wayne add

            $projectInfo = ProjectModel::info($apptoken);

            // 奖品总数量 奖品类别数量 判断
            $user = $this->user;
            $prizeCategoryNumber   = VipModel::getLevelExtraInfoByKey($this->user->id, 'editor_prize_category_numbers' );
            $prizeNumber = VipModel::getLevelExtraInfoByKey($this->user->id, 'editor_prize_numbers');
            if($inputPrizes && count($inputPrizes) > $prizeCategoryNumber) return response()->json(build_result('', '31004', ''));

            $inputPrizeNumber = 0;
            foreach ($inputPrizes as $key => $prize) {
                $inputPrizeNumber += $prize['lot_count'];
            }
            if($inputPrizeNumber > $prizeNumber)
                return response()->json(build_result('', '31005', ''));
            
            // **template.json更新**
            if($inputTemplateInfo) {
                TemplateJsonModel::write($apptoken, $inputTemplateInfo);
            }

            /***Settings 更新***/
            $settingInfo = array();
            $settingRows = SettingsModel::where(['appid' => $projectInfo->id, 'status' => SettingsModel::STATUS_ACTIVE]) ->get();
            if ($settingRows) {
                foreach ($settingRows as $rowNo=>$row) {
                    $item_key = $row['item_key'];
                    $item_value = $row['item_value'];
                    if($item_key == $this->_baseInfoKey) {
                    } else {
                        $settingInfo[$item_key] = $item_value;
                    }
                }
            }
            unset($settingRows);

            //update setting  //can't update [raffletype endtime settranscode setscorelimit setlimittimes]
            SettingsModel::where(['appid' => $projectInfo->id, 'status' => SettingsModel::STATUS_ACTIVE])->update(["status" => SettingsModel::STATUS_DELETE]);
            $unUpdateKey = ['raffletype','endtime','settranscode','setscorelimit','setlimittimes'];
            $updateSettingInfo = array();
            $inputSettingInfo['rule_show'] = $inputRuleShow;
            foreach ($inputSettingInfo as $inputKey => $inputValue) {
                if(!in_array($inputKey, $unUpdateKey)) {
                    if(!isset($settingInfo[$inputKey]) || $settingInfo[$inputKey] == $inputValue) {
                        if($inputKey == $this->_formKey) {
                            $inputValue = json_encode($inputValue);
                        }
                        $updateSettingInfo[$inputKey] = $inputValue;
                    }
                }
            }

            //update baseinfo [marketinginfo shareinfo]
            $item_key = VipSettingsModel::getProductItemKey($this->user->id, $projectInfo->id, 3);
            $endTime = VipSettingsModel::getItemValue($this->user->id, $item_key, 0);
            if($endTime <= $this->time) {
                $inputMarketingInfo['isset'] = 0;
                $inputMarketingInfo['type'] = 4;
            }
            $updateSettingInfo[$this->_baseInfoKey] = json_encode([
                "marketinginfo" => $inputMarketingInfo,
                "shareinfo" => $inputShareInfo
                ]);
            

            $insertRows = array();
            foreach($updateSettingInfo as $item_key  => $item_value) {
                $insertRows[] = array(
                        'appid' => $projectInfo->id,
                        'item_key' => $item_key,
                        'item_value' => $item_value,
                        'status' => SettingsModel::STATUS_ACTIVE,
                        'create_time' => $this->time,
                        'modify_time => 0'
                    );
            }
            SettingsModel::create($insertRows);
            unset($insertRows, $updateSettingInfo);

            //update prize
            if($inputPrizes) 
            {
                $updateRows = array();
                $insertRows = array();
                LotteryPrizeModel::select(["appid" => $projectInfo->id, "status" => LotteryPrizeModel::STATUS_ACTIVE])->update(["status" => LotteryPrizeModel::STATUS_DELETE, "modify_time" => $this->time]);
                foreach ($inputPrizes as $itemId => $item) {
                    if (!empty($item['lot_code_setting'])) {
                        if (is_array($item['lot_code_setting']) || is_object($item['lot_code_setting'])) {
                            if(isset($item['lot_code_setting']['num'])) $item['lot_code_setting']['num'] = $item['lot_count'];
                        }
                    }

                    if($item['id']) {
                        //update item
                        LotteryPrizeModel::where(['id' => $item['id']])->update([
                            "lot_id" => 0,
                            "lot_name" => $item['lot_name'],
                            "lot_count" => $item['lot_count'],
                            "probability" => $item['probability'],
                            "lot_desc" => $item['lot_desc'],
                            "lot_url" => $item['lot_url'],
                            "prizes_link" => $item['prizes_link'],
                            "lot_type" => $item['lot_type'],
                            "lot_winning_tips" => $item['lot_winning_tips'],
                            "lot_code_setting" => json_encode($item['lot_code_setting']),
                            "status" => LotteryPrizeModel::STATUS_ACTIVE,
                            "modify_time" => $this->time
                            ]);
                    } else {
                        //insert item //gamecode
                        $prizeObject = LotteryPrizeModel::create([
                            "appid" => $projectInfo->id,
                            "lot_id" => 0,
                            "lot_name" => $item['lot_name'],
                            "lot_count" => $item['lot_count'],
                            "lot_consume" => 0,
                            "probability" => $item['probability'],
                            "lot_desc" => $item['lot_desc'],
                            "lot_url" => $item['lot_url'],
                            "prizes_link" => $item['prizes_link'],
                            "lot_type" => $item['lot_type'],
                            "lot_winning_tips" => $item['lot_winning_tips'],
                            "lot_code_setting" => json_encode($item['lot_code_setting']),
                            "status" => LotteryPrizeModel::STATUS_ACTIVE,
                            "create_time" => $this->time,
                            "modify_time" => 0,
                            ]);
                        if ($prizeObject->id && ($item['lot_type'] == $MarketingModel::TYPE_EXCHANGE || $item['lot_type'] == $MarketingModel::TYPE_CROWD || $item['lot_type'] == $MarketingModel::TYPE_CROWDEXCHANGE || $item['lot_type']==$MarketingModel::TYPE_RAFFLE_SIGNED_EXCHANGE )) {
                            GameCodeModel::import($projectInfo->id, $prizeObject->id, $item['lot_code_setting'], $item['lot_count']);
                        }
                    }
                }
            }

            //update projectinfo  update[raffletype settranscode setwxredpack modify_time, title,desc]
            $updateData = array();
            if($inputRaffletype != $projectInfo->raffletype) $updateData['raffletype'] = $inputRaffletype;
            if($settingInfo['settranscode'] != $projectInfo['settranscode']) $updateData['raffletype'] = $inputRaffletype;
            if($inputShareInfo['title'] != $projectInfo['title']) $updateData['title'] = $inputShareInfo['title'];
            if($inputShareInfo['desc'] != $projectInfo['desc']) $updateData['desc'] = $inputShareInfo['desc'];
            if(!empty($updateData))
                ProjectModel::where(["id"=>$projectInfo->id])->update($updateData);
            unset($updateData);
            
            // delete redis cache projectinfo,baseinfo,shareinfo,marketinginfo
            CacheModel::del([
                "project:".$projectInfo->id,
                "project:".$apptoken
                ]);
            return response()->json(build_result(["status" => 1]));
        }catch(\Exception $e) {
            return response()->json(build_result('', '10001', $e->getMessage()));
        }
    }

    /**
     * 获取编辑页面信息
     * part1 编辑第一步信息 templateinfo
     * 直接获取template.json文件
     * 活动自动打开
     */
    public function templateinfo(Request $request)
    {
        try{
            $this->validate($request, [
                'apptoken' => 'required'
            ]);
            $apptoken = $request->input('apptoken');
            $projectInfo = ProjectModel::info($apptoken);
            $json = TemplateJsonModel::read($apptoken, $projectInfo->name);

            set_sharding_info($projectInfo->id, 1);
            $row = SettingsModel::where(['appid'=>$projectInfo->id, 'item_key' => 'rule_show', 'status'=>SettingsModel::STATUS_ACTIVE])->get();
			$ruleShow = $row[0]->item_value ? $row[0]->item_value : 0;
            return response()->json(build_result(["info" => [
                "ruleshow" => $ruleShow,
                "templateinfo" => $json
                ]]));
        } catch(\Exception $e) {
            return response()->json(build_result('', '10001', $e->getMessage()));
        }
    }


    /**
     * 获取编辑页面信息
     * part2 获取编辑第二步信息
     */
    public function lotteryinfo(Request $request)
    {
        try{
            $this->validate($request, [
                'apptoken' => 'required'
            ]);
            $apptoken = $request->input('apptoken');
            $projectInfo = ProjectModel::info($apptoken);
            $templateInfo = TemplateModel::info_by_id($projectInfo->template_id);

            $marketType = $projectInfo->raffletype;
            $raffletypes    = MarketingModel::TYPE_NONE;
            $raffletypeArrs = explode(',', $templateInfo->raffletypes);

            if(!$marketType) {
                if(is_array($raffletypeArrs)) {
                    //默认营销类型设置
                    if (in_array(MarketingModel::TYPE_RAFFLE, $raffletypeArrs)) {
                        $marketType = MarketingModel::TYPE_RAFFLE;
                    } else {
                        $marketType = $raffletypeArrs[0];
                    }
                } else {
                    $marketType = MarketingModel::TYPE_NONE;
                }
            }

            $templateType = MarketingModel::getMarketTypeName();
            $templateTypeName = array();
            if(count($templateType) > 0) {
                foreach ($raffletypeArrs as $val) {
                    $val = MarketingModel::getMarketMap($val);
                    if(isset($templateType[$val])) {
                        $templateTypeName[$val] = $templateType[$val];
                    }
                }
            }
            $templateTypeName = array_unique($templateTypeName);
            $marketTypeName = $templateType[$marketType];
            list($settingInfo, $prizes, $forms) = $this->$marketTypeName($projectInfo, $templateInfo);

            return response()->json(build_result(["prizes"=>$prizes, "settinginfo"=>$settingInfo,'templatetypes' => $templateTypeName, 'markettypeName'=>$marketTypeName, 'forms'=> $forms, 'raffletype' => $marketType]));
        } catch(\Exception $e) {
            return response()->json(build_result('', '10001', $e->getMessage()));
        }
    }

    /*选择营销方式-排行榜*/
	protected function rank($projectInfo, $templateInfo) 
	{
		set_sharding_info($projectInfo->id, 1);
        $prizes      = array();
        $settingInfo = array();

        $settingRows = SettingsModel::where(['appid' => $projectInfo->id, 'status' => SettingsModel::STATUS_ACTIVE]) ->get();
        if ($settingRows) {
            foreach ($settingRows as $rowNo=>$row) {
                $item_key = $row['item_key'];
                $item_value = $row['item_value'];
                if($item_key == $this->_baseInfoKey) {
                    $item_value = json_decode($item_value, true);
                    $settingInfo[$item_key] = $item_value;
                } else {
                    $settingInfo[$item_key] = $item_value;
                }
            }
        }
        //获取奖项信息
        $prizeRows = LotteryPrizeModel::where(["appid" => $projectInfo->id, "status" => LotteryPrizeModel::STATUS_ACTIVE])->get();
        
        if($prizeRows)$prizes = array_values(json_decode(json_encode($prizeRows), true));
        unset($prizeRows);
        if(is_array($prizes)) {
            foreach ($prizes as $value) {
                $lotSet = json_decode($value['lot_code_setting'], true);
                $value['firstnum'] = isset($lotSet['firstnum']) ? $lotSet['firstnum'] : '';
                $value['lastnum'] = isset($lotSet['lastnum']) ? $lotSet['lastnum'] : '';
                unset($value['lot_code_setting']);
                $prizes[] = $value;
            }
        }
        $forms = FormDictModel::getAllItems($projectInfo->id, $this->user->id);
        return [$settingInfo, $prizes, $forms];
	}

    //*选择营销方式-抽奖*/
    protected function raffle($projectInfo, $templateInfo)
    {
        set_sharding_info($projectInfo->id, 1);
        $prizes      = array();
        $settingInfo = array();

        $settingInfo[$this->_formKey]   = FormDictModel::DEFAULT_KEY;
        $settingRows = SettingsModel::where(['appid' => $projectInfo->id, 'status' => SettingsModel::STATUS_ACTIVE]) ->get();

        foreach ($settingRows as $rowNo => $row) {
            $item_key = $row['item_key'];
            $item_value = $row['item_value'];

            if(!in_array($item_key, $this->_unsetSettingsKey)) {
                if($item_key == $this->_formKey) {
                    $settingInfo[$this->_formKey] = $row ? json_decode($row, true) : $settingInfo[$this->_formKey];
                } elseif ($item_key == $this->_baseInfoKey) {
                    $settingInfo[$this->_baseInfoKey] = json_decode($row, true);
                } else {
                    $settingInfo[$item_key] = $item_value;
                }
            }
        }

        $settingInfo['setscorelimit'] = $templateInfo->setscorelimit ? $templateInfo->setscorelimit : 0;
        $settingInfo['setlimittimes'] = $templateInfo->setlimittimes ? $templateInfo->setlimittimes : 0;
        //七夕模板特殊设置|设置匹配度参数
        if($settingInfo['setscorelimit'] == 2)  {
            $settingInfo['matchtimes'] = isset($settingInfo['matchtimes']) ? $settingInfo['matchtimes'] : 3;
            $settingInfo['matchscore'] = isset($settingInfo['matchscore']) ? $settingInfo['matchscore'] : 80;
        }

        $isQd = (int) $templateInfo->is_signed; // 是否为签到类型模版
        if($isQd) $settingInfo['winrepeattimes'] = -1 ; // 签到类型模版不允许重复中奖
        if($templateInfo->name == 'shengdanheti') $settingInfo['winrepeattimes'] = 1; // 圣诞合体默认允许中奖次数为1

        //设置每天参与机会
        $settingInfo['isallowdailynum']    = (isset($settingInfo['isallowdailynum']) && (int)$settingInfo['isallowdailynum']>0) ? 1 : 0;
        //每天抽奖机会
        $settingInfo['dailylotterynum']    = isset($settingInfo['dailylotterynum']) ? (int)$settingInfo['dailylotterynum'] : 0;


        //获取奖项信息
        $prizeRows = LotteryPrizeModel::where(["appid" => $projectInfo->id, "status" => LotteryPrizeModel::STATUS_ACTIVE])->get();
		
        if($prizeRows)$prizes = array_values(json_decode(json_encode($prizeRows), true));
		unset($prizeRows);

        foreach ($prizes as $t => &$prize) {
            $lotId      = $prize['lot_id'];
            $lotType    = $prize['lot_type'];
            if(MarketingModel::getMarketMap($lotType) != MarketingModel::TYPE_RAFFLE) {
                //多余奖品清除
                unset($prizes[$t]);
                continue;
            }
            //处理奖项设置信息
            $lotSettingInfo = json_decode($prize['lot_code_setting'], true);

            switch ($lotType) {
                case MarketingModel::TYPE_RAFFLE_SIGNED_RAFFLE : //将签到模板奖品作为普通奖品处理
                    $prize['lot_type'] = MarketingModel::LOT_TYPE_RAFFLE;
                    $prize["lot_exchangenum"] = isset($lotSettingInfo['lot_exchangenum']) && $lotSettingInfo['lot_exchangenum']
                          ? $lotSettingInfo['lot_exchangenum'] : 0 ;
                    break;
                case MarketingModel::TYPE_RAFFLE_SIGNED_EXCHANGE : //将签到模板奖品作为普通奖品处理
                    $prize['lot_type'] = MarketingModel::LOT_TYPE_EXCHANGE;
                    $prize["lot_exchangenum"] = isset($lotSettingInfo['lot_exchangenum']) && $lotSettingInfo['lot_exchangenum']
                          ? $lotSettingInfo['lot_exchangenum'] : 0 ;
                    break;
                case MarketingModel::TYPE_RAFFLE_THIRD : //第三方处理链接地址
                    $exterUrl = str_replace(array(" ","  ","'",'"'), "", $prize['prizes_link']);
                    $prize['prizes_link'] = str_replace("&amp;", "&", $exterUrl);
                    break;
                case MarketingModel::TYPE_REDPACK : //微信红包处理红包金额
                    $prize["lot_unit_price"] = isset($lotSettingInfo['lot_unit_price']) && $lotSettingInfo['lot_unit_price']
                          ? $lotSettingInfo['lot_unit_price'] : 0 ;
                    $prize["lot_amount_price"] = isset($lotSettingInfo['lot_amount_price']) && $lotSettingInfo['lot_amount_price']
                          ? $lotSettingInfo['lot_amount_price'] : 0 ;
                    break;
            }

            if($isQd == 1 && !isset($prize["lot_exchangenum"])) {
                $prize["lot_exchangenum"] = isset($lotSettingInfo['lot_exchangenum']) && $lotSettingInfo['lot_exchangenum']
                ? $lotSettingInfo['lot_exchangenum'] : 0 ;
            }

            //qianglibao
            if($projectInfo->iscollect ==4){ 
                    //每个礼包奖品数
                    $lotSettingInfo['lot_gift_prizes']    = (isset($lotSettingInfo['lot_gift_prizes']) && $lotSettingInfo['lot_gift_prizes'])
                        ? $lotSettingInfo['lot_gift_prizes'] : 1;
                    //分钟
                    $lotSettingInfo['lot_gift_minute']    = (isset($lotSettingInfo['lot_gift_minute']) && $lotSettingInfo['lot_gift_minute'])
                        ? $lotSettingInfo['lot_gift_minute'] : 1;
                    //平分的人数
                    $lotSettingInfo['lot_gift_peoplenum'] = (isset($lotSettingInfo['lot_gift_peoplenum']) && $lotSettingInfo['lot_gift_peoplenum'])
                        ? $lotSettingInfo['lot_gift_peoplenum'] : 1;
             
            }
            $prize["lot_code_setting"] = $lotSettingInfo;
        }

        $settingInfo['formruledesc'] = $settingInfo['formruledesc']? $settingInfo['formruledesc'] :"恭喜您中奖啦~ 请填写下列信息，便于工作人员和您获取联系发放奖品";


        $settingInfo["setrankbtn"]  = $templateInfo->setrankbtn >0 ? 1 : 0;    //当前模板是否支持设置排行榜

        $isPublish  = $projectInfo->publish_platform>0 ? 1 : 0;
        //判断是否允许口令兑换
        $settingInfo['is_display_settranscode']    = ! in_array($projectInfo->name, $this->_noTransCode) && $isPublish ? 1 : 0; // 是否显示口令兑换输入框
        $settingInfo['settranscode']               = $projectInfo->settranscode; //是否勾选了口令兑换

        //判断是否允许微信红包
        $settingInfo['isShowWxRedpack'] = ! in_array($projectInfo->name, $this->_noWxRedPack) && $isPublish ? 1 : 0;

        //判断奖品数量是否有限制
        $settingInfo['isUnlimitPrize'] = in_array($projectInfo->name, array_keys($this->_noUnlimit)) || $isQd ? 1 : 0;
        $forms = FormDictModel::getAllItems($projectInfo->id, $this->user->id);
        return [$settingInfo, $prizes, $forms];
    }

    /*选择营销方式-表单*/
    protected function entry($projectInfo, $templateInfo)
    {
        $prizes = array();
        $settingInfo = array();

        $settingInfo[$this->_formKey]   = FormDictModel::DEFAULT_KEY;
        $settingRows = SettingsModel::where(['appid' => $projectInfo->id, 'status' => SettingsModel::STATUS_ACTIVE]) ->get();

        foreach ($settingRows as $rowNo => $row) {
            $item_key = $row['item_key'];
            $item_value = $row['item_value'];

            if($item_key == $this->_formKey) {
                $settingInfo[$this->_formKey] = $row ? json_decode($row, true) : $settingInfo[$this->_formKey];
            } elseif($item_key == 'formruledesc') {
                $settingInfo['formruledesc'] = $item_value;
            }
        }
        $forms = FormDictModel::getAllItems($projectInfo->id, $this->user->id);
        return [$settingInfo, $prizes, $forms];
    }

    /*选择营销方式-分享*/
    protected function share($projectInfo, $templateInfo)
    {
        return [array(), array(), array()];
    }

    /**
     * 获取编辑页面信息
     * part3 获取营销信息
     */
    public function marketinfo(Request $request)
    {
        try{
            $this->validate($request, [
                'apptoken' => 'required'
            ]);
            $apptoken = $request->input('apptoken');
            $projectInfo = ProjectModel::info($apptoken);
            $marketType = $projectInfo->raffletype;
            $templateInfo = TemplateModel::info_by_id($projectInfo->template_id);

            $settingRows = SettingsModel::where(['appid' => $projectInfo->id, 'status' => SettingsModel::STATUS_ACTIVE, 'item_key' => $this->_baseInfoKey]) ->get();

            $baseInfoRow = isset($settingRows[0]) ? $settingInfo[0] : array();
            unset($settingRows);
            $baseInfo = !empty($baseInfoRow) ? json_decode($baseInfoRow->item_value, true) : array();

            $marketingInfo = array(
                'isset'             => 0,
                'type'              => 4,
                'promotion_isset'   => 1,
                'promotion_type'    => 1,
                'linkname'          => '我也要用赢销+免费制作',
                'linkpath'          => 'http://www.beetobees.com/m/index.html?acode='.$apptoken,
                'unionname'         => '游戏化营销专家',
                'unionpath'         => 'http://www.beetobees.com/m/index.html?acode='.$apptoken,
                'basename'          => '赢销+技术支持',
                'basepath'          => 'http://www.beetobees.com/m/index.html?acode='.$apptoken,
                'qrcodeurl'         => 'adImg.png',
                'qrcodepath'        => 'qrcode.png',
                'redicturl'         => 'resource/assets/about.png',
                'redictpath'        => 'http://www.beetobees.com/m/index.html?acode='.$apptoken
            );

            $shareInfo = array(
                    "title"         => $projectInfo->title,
                    "desc"          => $projectInfo->desc,
                    "link"          => "icon.png",
                    "finishdesc"    => $templateInfo->share_finish_desc,
                    "endtime"       => $projectInfo->endtime
                );

            if(isset($baseInfo['marketinginfo'])) $marketingInfo = array_merge($marketingInfo, $baseInfo['marketinginfo']);
            if(isset($baseInfo['shareinfo'])) $shareInfo = array_merge($shareInfo, $baseInfo['shareinfo']);

            if(!$marketingInfo['isset']) {
                $item_key = VipSettingsModel::getProductItemKey($this->user->id, $projectInfo->id, 3);
                $endTime = VipSettingsModel::getItemValue($this->user->id, $item_key, 0);
                if($endTime > $this->time) $marketingInfo['isset'] = 1;
            }

            //去除加载页文字广告
            $marketingInfo['loading_desc_price'] = 0;
            $item_key = VipSettingsModel::getProductItemKey($this->user->id, $projectInfo->id, 4);
            $endTime = VipSettingsModel::getItemValue($this->user->id, $item_key, 0);
            if($endTime > $this->time) $marketingInfo['loading_desc_price'] = 1;

            return response()->json(build_result([
                "marketinginfo" => $marketingInfo,
                "shareinfo" => $shareInfo
            ]));
        } catch(\Exception $e) {
            return response()->json(build_result('', '10001', $e->getMessage()));
        }
    }
}
